package com.rzico.basics.amap.util;

import com.alibaba.fastjson.JSONObject;
import com.rzico.basics.amap.pojo.response.IPLocationResponse;

/**
 * IP定位
 * <p>
 * Created by lam on 2018/8/8.
 */
public class GeoIPLocationUtil {

    // 行政区域查询API服务地址
    private static String map_ip_url = "https://restapi.amap.com/v3/ip?parameters";

    /**
     * 根据IP查询地理信息
     *
     * @param ip
     * @return
     */
    public static IPLocationResponse searchGeoDistrict(String key, String ip) {
        IPLocationResponse response = null;

        if (key == null || "".equals(key)) {
            response = new IPLocationResponse();
            response.setError(true);
            response.setMessage("高德key为空");
            return response;
        }

        if (ip == null || "".equals(ip)) {
            response = new IPLocationResponse();
            response.setError(true);
            response.setMessage("请输入需要查询的区域参数");
            return response;
        }

        try {
            String result = OKHttpUtil.httpGet(map_ip_url.replace("parameters", "") + "key=" + key + "&ip=" + ip);
            response = JSONObject.parseObject(result, IPLocationResponse.class);

            if (response != null && response.getStatus() == 0) {
                response.setError(true);
                response.setMessage(response.getInfo());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

}
